<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表 </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告区域  -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域   -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品区域的级联样式框 -->
          <el-cascader
            clearable
            v-model="selectKeys"
            :options="cateList"
            :props="cascaderprops"
            @change="partentCateChange"
          ></el-cascader>
          <!-- tabs标签切换 -->
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="动态参数" name="many">
              <!-- 添加参数的按钮  -->
              <el-button
                @click="adddialogVisible = true"
                :disabled="isBtnDisabled"
                type="primary"
                size="mini"
                >添加参数</el-button
              >
              <!-- 动态参数表格 -->
              <el-table :data="manyTabDate" border stripe>
                <!-- 展开行    -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close="handleClose(i, scope.row)"
                      >{{ item }}</el-tag
                    >
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引行 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column
                  label="参数名称"
                  prop="attr_name"
                ></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <!-- 修改按钮 -->
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="showEditDialog(scope.row.attr_id)"
                    ></el-button>
                    <!-- 删除按钮 -->
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="RemoveUserById(scope.row.attr_id)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
              <!-- 添加属性的按钮  -->
              <el-button
                @click="adddialogVisible = true"
                :disabled="isBtnDisabled"
                type="primary"
                size="mini"
                >添加属性</el-button
              >
              <el-table :data="manyTabDate" border stripe>
                <!-- 展开行    -->
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item, i) in scope.row.attr_vals"
                      :key="i"
                      closable
                      @close="handleClose(i, scope.row)"
                      >{{ item }}</el-tag
                    >
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </template>
                </el-table-column>
                <!-- 索引行 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column
                  label="属性名称"
                  prop="attr_name"
                ></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <!-- 修改按钮 -->
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="showEditDialog(scope.row.attr_id)"
                    ></el-button>
                    <!-- 删除按钮 -->
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="RemoveUserById(scope.row.attr_id)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="addFormClose"
    >
      <el-form
        ref="addParamsRef"
        :model="addParamsForm"
        :rules="addParamsRules"
        label-width="100px"
      >
        <el-form-item prop="attr_name" :label="titleText">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="addFormClose"
    >
      <el-form
        ref="addParamsRef"
        :model="editParamsForm"
        :rules="editParamsRules"
        label-width="100px"
      >
        <el-form-item prop="attr_name" :label="titleText">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      inputVisible: false,
      inputValue: '',
      editParamsForm: {},
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入静态属性', trigger: 'blur' },
        ],
      },
      addParamsForm: {
        attr_name: '',
      },
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      cateList: [],
      // 级联样式表数据
      selectKeys: [],
      cascaderprops: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: 'true',
      },
      //   被激活页面的名称
      activeName: 'many',
      // 区分only，many
      onlyTabDate: [],
      manyTabDate: [],
      adddialogVisible: false,
      editdialogVisible: false,
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return res.$message.error('获取商品分类失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)
    }, // 抽取方法，获取参数列表
    async getParamsData() {
      // 不允许选中1,2级权限修改
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        // 更改查询权限，重置参数项
        this.onlyTabDate = []
        this.manyTabDate = []
        return
      }
      console.log(this.selectKeys)
      // 根据所选分类的id cateid（）和当前所处的属性面板name，获取参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // 获取参数下的可选项,逗号分割数据 ,
      // 字符串切割会匹配切割空字符串，三元解决匹配空字符串的问题，转空数组解决
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      console.log(res.data)
      if (res.data === 'only') {
        this.onlyTabDate = res.data
      } else {
        this.manyTabDate = res.data
      }
    }, // 级联样式表change事件
    partentCateChange() {
      this.getParamsData()
    }, // tab栏切换触发事件
    handleTabClick() {
      console.log(this.activeName)
      this.getParamsData()
    }, // 关闭对话框重置文本
    addFormClose() {
      this.$refs.addParamsRef.resetFields()
    }, // 添加参数
    addParams() {
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) return
        // 预校验通过
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        console.log(res.data)
        if (res.meta.status !== 201) {
          return this.$message.error('添加操作失败')
        }
        this.adddialogVisible = false
        this.$message.success('添加操作成功')
        this.getParamsData()
      })
    }, // 获取编辑参数
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: { attr_sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.editParamsForm = res.data
      this.editdialogVisible = true
    }, // 提交编辑请求
    editParams() {
      // 表单预校验
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }
        this.$message.success('更新成功')
        this.getParamsData()
        this.editdialogVisible = false
      })
    }, // 删除按钮事件
    async RemoveUserById(id) {
      const removeResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // 捕捉错误
      // console.log(removeResult) // confirm | cancel
      if (removeResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 删除操作
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getParamsData()
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(() => {
        // 箭头函数里面无参数可以写成() 或 _
        this.$refs.saveTagInput.focus()
      })
    }, // 文本框失去焦点或者按下enter键触发事件
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 如果没有return出去，说明输入的内容需要做后续处理
      // 先将输入的值推送到attr_vals，清空输入框，关闭输入框
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 调用接口，完成数据推送，重新渲染界面
      this.saveAttrVals(row)
    }, // 监听参数项删除事件
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    async saveAttrVals(row) {
      // 调用接口，完成数据推送，重新渲染界面
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(','),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新数据失败')
      }
      this.$message.success('添加参数项成功')
    },
  },
  //   计算属性
  computed: {
    isBtnDisabled() {
      // 如果selectkeys的长度不为3，说明不是3级标签，禁用按钮
      // 反之，开启按钮6611
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    }, // 获取当前三级分类的id
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    }, // 弹出添加参数对话框
    titleText() {
      if (this.activeName === 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    },
  },
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 15px;
}
.input-new-tag {
  width: 130px;
}
</style>
